/*
 * @Author: 吴世扬
 * @Date: 2022-09-10 17:43:55
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-05-23 16:03:20
 * @FilePath: /vue3-admin/src/plugins/permission.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from '@/router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken, setCookieToken } from '@/utils/auth';
import { usePermissionStore } from '@/store/index';
import { useMy } from '@/service/useMy';
import { NO_PERMISSION_REDIRECT_PATH } from '@/constants';

export const setupPermission = () => {
    NProgress.configure({ showSpinner: false }); // 进度环显示/隐藏

    const { updateUserStoreMyInfo } = useMy();
    const permission = usePermissionStore();

    // 白名单路由
    const whiteList = ['/login'];

    router.beforeEach(async (to, from, next) => {
        NProgress.start();
        if (typeof to.meta.title === 'string') {
            // 设置名称
            document.title = to.meta.title;
        }
        if (whiteList.includes(to.path)) {
            next();
        } else {
            const token = getToken();
            if (token) {
                if (permission.needUpdate) {
                    await updateUserStoreMyInfo();

                    // 更新权限
                    await permission.updateRoutes();

                    // if (userStore.needChangePw) {
                    //     ElMessage({
                    //         type: 'warning',
                    //         message: '您的密码未进行更改，请更改后再使用系统(登录密码必须8位（含8位）以上，至少包含字母和数字)',
                    //         duration: 3000
                    //     });
                    // }
                    // if (userStore.needChangePw) {
                    //     next('/userCenter/Info');
                    // } else {
                    //     next(toPath);
                    // }
                    // 设置图片cookie
                    setCookieToken(token);
                    permission.needUpdate = false;
                    next(to.fullPath);
                } else {
                    let toPath = to.fullPath;
                    // 判断是否有权登录
                    if (!permission.hasRouteAuth(to.path)) {
                        toPath = NO_PERMISSION_REDIRECT_PATH;
                    }
                    if (toPath === to.fullPath) {
                        next();
                    } else {
                        next(toPath);
                    }
                }
            } else {
                next(
                    `/login?redirect=${to.path === '/login' ? '/' : to.fullPath}`
                ); // 否则全部重定向到登录页
            }
        }
        NProgress.done();
    });
};
